package concurrent;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TwoInterruptDemo {
    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination termination = new TwoPhaseTermination();
        termination.start();
        Thread.sleep(3500);
        termination.stop();
    }
}

/**
 * 两阶段终止模式
 */
@Slf4j(topic = "t.TwoPhaseTermination")
class TwoPhaseTermination {
    private Thread monitor;

    //启动监控线程
    public void start() {
        monitor = new Thread(() -> {
            while (true) {
                Thread current = Thread.currentThread();
                if (current.isInterrupted()) {
                    log.info("ending...");
                    break;
                }
                try {
                    Thread.sleep(1000);
                    log.debug("exec monitor");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    current.interrupt();
                }
            }
        });
        monitor.start();
    }

    //停止监控线程
    public void stop() {
        monitor.interrupt();
    }
}
